package com.yuanfengerp.IncomeItem.service.impl;


import com.yuanfengerp.IncomeItem.dao.IncomeItemInfoMapper;
import com.yuanfengerp.IncomeItem.entity.IncomeItemInfo;
import com.yuanfengerp.IncomeItem.service.IncomeItemInfoService;
import com.yuanfengerp.publicUtil.Result;
import com.yuanfengerp.publicUtil.SnowflakeIdWorker;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class IncomeItemInfoServiceImpl implements IncomeItemInfoService {
    @Autowired
    private IncomeItemInfoMapper iiim;
    SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1);

    @Override
    public Result<String> deleteByPrimaryKey(String income_ID) {
        int i = iiim.deleteByPrimaryKey(income_ID);
        return i > 0 ? Result.success("删除成功") : Result.failure(500, "删除失败");
    }

    @Override
    public Result<String> insertIncomeItemInfo(IncomeItemInfo incomeItemInfo) {
        incomeItemInfo.setIncome_operate_time(new Timestamp(System.currentTimeMillis()));
        incomeItemInfo.setIncome_review_time(new Timestamp(System.currentTimeMillis()));
        incomeItemInfo.setIncome_ID(snowflakeIdWorker.nextId());
        System.out.println(incomeItemInfo.toString());
        int i = iiim.insertIncomeItemInfo(incomeItemInfo);
        return i > 0 ? Result.success("添加成功") : Result.failure(500, "添加失败");
    }

    @Override
    public Result<String> updateIncomeItemInfo(IncomeItemInfo incomeItemInfo) {
        incomeItemInfo.setIncome_review_time(new Timestamp(System.currentTimeMillis()));
        int i = iiim.updateIncomeItemInfo(incomeItemInfo);
        return i > 0 ? Result.success("修改成功") : Result.failure(500, "修改失败");
    }

    @Override
    public Result<List<IncomeItemInfo>> selectAllIncomeItemInfo(@Param("pageSize") Integer pageSize, @Param("pageNum") Integer pageNum) {
        Logger logger = LoggerFactory.getLogger(this.getClass());

        try {
            if (iiim == null) {
                logger.error("ipmim is null");
                return Result.failure(500, "内部错误");
            }
            int totalRecords = iiim.getTotalCount();
//            Integer pageNum = (Integer) params.get("pageNum");
//            Integer pageSize = (Integer) params.get("pageSize");
            // 获取总记录数，这里假设传入了合适的查询参数（如param1和param2）
            if (pageNum == null)
                pageNum = 5;
            if (pageSize == null)
                pageSize = 1;
            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalRecords / pageNum);

            // 判断页码是否超出范围
            if (pageSize > totalPages)
                return Result.failure(400, "页码超出有效范围");
            pageSize = (pageSize - 1) * pageNum;
            List<IncomeItemInfo> payMethodInfos = iiim.selectAllIncomeItemInfo(pageSize, pageNum);

            if (payMethodInfos != null) {
                logger.info("Successfully retrieved pay method info list");
                return Result.success(payMethodInfos);
            } else {
                logger.warn("No data found");
                return Result.failure(404, "没有数据");
            }
        } catch (Exception e) {
            logger.error("Error occurred while selecting all pay method info", e);
            return Result.failure(500, "内部错误");
        }
    }

    @Override
    public Result<List<IncomeItemInfo>> selectIncomeItemInfo(Map<String, Object> params) {
        Logger logger = LoggerFactory.getLogger(this.getClass());


        int totalRecords = iiim.getTotalCountINS((String) params.get("income_ID"),
                (String) params.get("income_name"),(Integer) params.get("income_state"));
        Integer pageNum = (Integer) params.get("pageNum");
        Integer pageSize = (Integer) params.get("pageSize");
        try {
            if (iiim == null) {
                logger.warn("ipmim is null");
                return Result.failure(500, "内部错误");
            }
            if (pageNum == null) {
                pageNum = 1;
            }
            if (pageSize == null) {
                pageSize = 10;
            }

            int totalPages = (totalRecords + pageNum - 1) / pageNum;

            if (pageNum < 1 || pageNum > totalPages) {
                return Result.failure(400, "页码超出有效范围");
            }

            int offset = (pageNum - 1) * pageSize;
            params.put("offset", offset);
            List<IncomeItemInfo> payMethodInfos = iiim.selectIncomeItemInfo(params);

            if (payMethodInfos != null) {
                logger.info("Successfully retrieved {} pay method info records", payMethodInfos.size());
                return Result.success(payMethodInfos);
            } else {
                logger.warn("No data found for page {} with size {}", pageNum, pageSize);
                return Result.failure(404, "没有数据");
            }
        } catch (NullPointerException e) {
            logger.error("Null pointer exception occurred", e);
            return Result.failure(500, "内部错误");
        }
        catch (Exception e) {
            logger.error("Unexpected error occurred", e);
            return Result.failure(500, "内部错误");
        }
    }
}
